import type { Router } from 'vue-router';
import { useUserStore } from '@/stores';
const { roles, isAuthenticated } = useUserStore();
import { RouteNames } from '@/routes/names';

export function setupPermissionGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore();

    // 1. 检查是否登录
    if (to.meta.requiresAuth && !isAuthenticated) {
      next({ name: RouteNames.LOGIN, query: { redirect: to.fullPath } });
      return;
    }

    // 2. 已登录时访问登录页重定向到首页
    if (to.name === RouteNames.LOGIN && isAuthenticated) {
      next({ path: '/' });
      return;
    }

    // 3. RBAC 权限检查
    if (to.meta.roles) {
      const userRoles = userStore.roles || [];
      const hasPermission = to.meta.roles.some(role => userRoles.includes(role));

      if (!hasPermission) {
        next({ name: RouteNames.FORBIDDEN });
        return;
      }
    }

    next();
  });
}
